import { Component, OnInit } from '@angular/core';
import {CourseEvaluateService} from './course-evaluate.service';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {PageEntity} from '../../../core/domain/page.entity';
import {StatusEnum} from '../../../core/enum/status.enum';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {FilterEnum} from '../../../core/enum/filter.enum';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import {StorageUtil} from '../../../utils/storage.util';
import {Observable, Observer} from 'rxjs';
import {SourceServer} from '../../../common/source.server';
import {DatePipe} from '@angular/common';

@Component({
  selector: 'app-course-evaluate',
  templateUrl: './course-evaluate.component.html',
  styleUrls: ['./course-evaluate.component.scss'],
  providers: [CourseEvaluateService, SourceServer, DatePipe]
})
export class CourseEvaluateComponent implements OnInit {
  pageInfo: PageEntity = new PageEntity();
  tabList = [
    { text: '全部', value: ''},
    { text: '已评价', value: '已评价'},
    { text: '未评价', value: '未评价'},
  ];
  dataList = [];
  nzWidthConfigs = [];
  searchParams: SearchParams = new SearchParams();
  yearList = [];
  semesterList = [];
  view = false;
  evaluateTableObj: EvaluateTableObj = new EvaluateTableObj();
  evaluateObj: any = {};
  assessmentPersonArr = [
    {label: '学院领导', value: '学院领导', checked: false},
    {label: '督导员', value: '督导员', checked: false},
    {label: '系部负责人', value: '系部负责人', checked: false},
    {label: '职能部门负责人', value: '职能部门负责人', checked: false},
  ];
  checkerRole = [];
  evaluateProjectList = [];
  evaluateProjectNoScoreList = [];
  rowSpanIndexArr = [];
  tdHiddenIndexArr = [];
  totalScore = 0;
  uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
  headerInfo = null;
  linkInfo = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`;
  fileList = [];
  constructor(
    private http: CourseEvaluateService,
    private message: NzMessageService,
    private sourceServer: SourceServer,
    private datePipe: DatePipe
  ) { }

  ngOnInit() {
    this.headerInfo = StorageUtil.getFileHeader();
    this.getSchoolYearList();
  }

  /**
   * 获取学年学期
   */
  getSchoolYearList() {
    this.http.getSchoolYearApi().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.yearList = res.datas;
        res.datas.map(item => {
          if (item.currSchoolYear) {
            // this.searchParams.schoolYear = item.schoolYear;
            this.semesterList = item.semester;
            item.semester.map(ele => {
              if (ele.currSemester) {
                // this.searchParams.semester = ele.semester;
              }
            });
          }
        });
        this.clickSearch();
      }
    });
  }


  page(page) {
    this.pageInfo.filters.isSelf = PaginationUtils.filters(1, FilterEnum.EQUALS);
    this.pageInfo.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.http.page(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.dataList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
        this.nzWidthConfigs = [
          '60px', '150px', '150px', '100px', '150px', '150px',
          '100px', '100px', '180px', '100px', '100px',
          '100px', '150px', '200px',
          '100px', '100px'
        ];
      }
    });
  }

  /**
   * 点击查询
   */
  clickSearch() {
    for (const o in this.searchParams) {
      if (this.searchParams[o]) {
        this.pageInfo.filters[o] = PaginationUtils.filters(this.searchParams[o], FilterEnum.CONTAINS);
      } else {
        delete this.pageInfo.filters[o];
      }
      if (this.searchParams.semester === 0) {
        this.pageInfo.filters.semester = PaginationUtils.filters(this.searchParams.semester, FilterEnum.EQUALS);
      }
    }
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  /**
   * 点击重置
   */
  resetSearch() {
    this.searchParams = new SearchParams();
    this.pageInfo = new PageEntity();
    this.clickSearch();
  }

  changePageIndex(index) {
    this.pageInfo.first = index;
    this.page(this.pageInfo);
  }

  changePageSize(size) {
    this.pageInfo.first = 1;
    this.pageInfo.rows = size;
    this.clickSearch();
  }

  /**
   * 点击切换选中tab
   */
  changeTab(data) {
    if (data.value === this.searchParams.state) { return false; }
    this.pageInfo = new PageEntity();
    this.searchParams = new SearchParams();
    this.searchParams.state = data.value;
    this.clickSearch();
  }

  /**
   * 点击评价
   */
  clickEvaluated(data) {
    this.http.getEvaluateApi({
      id: data.id
    }).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.view = true;
        this.evaluateObj = res.datas;
        this.evaluateProjectList = [];
        this.evaluateProjectNoScoreList = [];
        this.rowSpanIndexArr = [];
        this.tdHiddenIndexArr = [];
        this.totalScore = 0;
        this.fileList = [];
        this.checkerRole = [];
        this.assessmentPersonArr.map(item => {
          item.checked = false;
        });
        this.evaluateTableObj = new EvaluateTableObj();
        (res.datas.classifyList || []).map(item => {
          if (item.detailList) {
            // 有分数，有选项
            (item.detailList || []).map(ele => {
              this.evaluateProjectList.push({
                hasItem: true,
                rowInfo: { ...ele },
                ...item
              });
            });
          } else if (item.examClassifyScore) {
            // 有分数，无选项
            this.evaluateProjectList.push({
              hasItem: false,
              rowInfo: {...item},
              ...item
            });
          } else {
            // 无分数
            this.evaluateProjectNoScoreList.push({
              rowInfo: item,
              ...item
            });
          }
        });
        console.log(this.evaluateProjectList);
        let totalNum = 0;
        this.evaluateProjectList.map((item, index) => {
          if (item.detailList) {
            if (totalNum === index) {
              this.rowSpanIndexArr.push(item.detailList.length);
              totalNum += item.detailList.length;
              this.tdHiddenIndexArr.push(totalNum);
            } else {
              this.rowSpanIndexArr.push(0);
            }
          } else {
            this.tdHiddenIndexArr.push(totalNum += 1);
          }
        });
        this.tdHiddenIndexArr.unshift(0);
      }
    });
  }

  /**
   * 量化评分发生改变时
   */
  changeEvaluateScore(value, index) {
    this.totalScore = 0;
    setTimeout(() => {
      this.evaluateProjectList.map((ele, i) => {
        this.totalScore += ele.getScore;
      });
    }, 200);
  }

  /**
   * 删除上传资源
   * @param file s
   */
  deleteFlile = (file: UploadFile) => {
    this.fileList.forEach((item, index) => {
      if (item.uid === file.uid) {
        // 调用后台删除图片
        this.fileList.splice(index, 1);
        this.sourceServer.deleteFile([file.uid]).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success('文件删除成功!');
          }
        });
      }
    });
  }

  // 上传附件
  handleChange(event): void {
    const { file, fileList, type} = event;
    if (type === 'success') {
      if (file.response.status === StatusEnum.SUCCESS) {
        fileList.forEach((item) => {
          if (item.response) {
            const datas = item.response.datas;
            item.uid = datas.id;
            item.url = this.linkInfo + 'source/view/' + datas.moduleName + '/' + datas.fileNewName;
          }
        });
        this.fileList = fileList;
      } else {
        this.message.warning('文件上传失败,请重新上传!');
        this.fileList = [];
      }
    } else if (type === 'error') {
      this.fileList = [];
    }
  }

  /**
   * 选择课评人员
   */
  changeAssessment(value) {
    this.checkerRole = [];
    value.map(item => {
      if (item.checked) {
        this.checkerRole.push(item.value);
      }
    });
  }

  /**
   * 点击确定
   */
  clickConfirm() {
    if (!this.evaluateTableObj.evaluteDate) {
      this.message.warning('评价日期不能为空');
      return false;
    }
    if (!this.evaluateTableObj.startSection) {
      this.message.warning('开始课节不能为空');
      return false;
    }
    if (!this.evaluateTableObj.endSection) {
      this.message.warning('结束课节不能为空');
      return false;
    }
    if (this.evaluateTableObj.missCount + this.evaluateTableObj.realCount !== this.evaluateTableObj.shouldCount) {
      this.message.warning('缺课人数 + 实到人数 必须等于 应到人数');
      return false;
    }
    // 数据变换，构建classifyList参数
    const classifyList = [];
    const detailList = [];
    let valueFlag = false;
    this.tdHiddenIndexArr.map((item, index) => {
      const detailListItem = [];
      if (index + 1 < this.tdHiddenIndexArr.length) {
        this.evaluateProjectList.slice(item, this.tdHiddenIndexArr[index + 1]).map(ele => {
          detailListItem.push({
            content: ele.rowInfo.content,
            id: ele.rowInfo.id,
            examItemId: ele.rowInfo.examItemId,
            value: ele.rowInfo.type === '多选框' ? (ele.rowInfo.value || []).join('/') : ele.rowInfo.value,
            type: ele.rowInfo.type,
            selectStr: ele.rowInfo.selectStr
          });
          if (ele.rowInfo.type === '多选框') {
            if ((ele.rowInfo.value || []).includes('其他')) {
              if (!ele.rowInfo.content) {
                valueFlag = true;
              }
            } else if ((ele.rowInfo.value || []).length === 0) {
              valueFlag = true;
            }
          }
          if (ele.rowInfo.type === '单选框') {
            if (ele.rowInfo.value === '其他') {
              if (!ele.rowInfo.content) {
                valueFlag = true;
              }
            } else if (!ele.rowInfo.value) {
              valueFlag = true;
            }
          }
          if (ele.rowInfo.type === '文本框') {
            if (!ele.rowInfo.value) {
              valueFlag = true;
            }
          }
        });
        detailList.push(detailListItem);
      }
    });
    if (valueFlag) {
      this.message.warning('评价记录存在空值');
      return false;
    }
    let scoreFlag = false;
    this.tdHiddenIndexArr.map((item, index) => {
      this.evaluateProjectList.map((ele, i) => {
        if (item === i) {
          classifyList.push({
            content: ele.content,
            detailList: detailList[index],
            examClassifyId: ele.examClassifyId,
            getScore: ele.getScore,
            id: ele.id
          });
          if (!ele.getScore) {
            scoreFlag = true;
          }
        }
      });
    });
    this.evaluateProjectList.map(item => {
      if (!item.hasItem) {
        classifyList.map((ele, index) => {
          // 替换重复数据
          if (ele.examClassifyId === item.examClassifyId) {
            classifyList.splice(index, 1, {
              content: item.rowInfo.content,
              detailList: item.detailList,
              examClassifyId: item.examClassifyId,
              getScore: item.getScore,
              id: item.id
            });
          }
        });
      }
    });
    this.evaluateProjectNoScoreList.map(item => {
      classifyList.push({
        content: item.rowInfo.content,
        detailList: item.detailList,
        examClassifyId: item.examClassifyId,
        getScore: item.getScore,
        id: item.id
      });
    });
    if (scoreFlag) {
      this.message.error('量化评分不能为空');
      return false;
    }
    const sourceIdList = [];
    this.fileList.map(item => {
      sourceIdList.push(item.uid);
    });
    const obj = {
      cotherProblem: '',
      courseId: this.evaluateObj.courseId,
      courseName: this.evaluateObj.courseName,
      cproblem: '',
      ctrack: '',
      examCourseId: this.evaluateObj.examCourseId,
      id: this.evaluateObj.id,

      checkerRole: this.checkerRole.join(','),
      classifyList,
      evaluteDate: this.datePipe.transform(this.evaluateTableObj.evaluteDate, 'yyyy-MM-dd'),
      endSection: this.evaluateTableObj.endSection,
      startSection: this.evaluateTableObj.startSection,
      shouldCount: this.evaluateTableObj.shouldCount,
      realCount: this.evaluateTableObj.realCount,
      lateCount: this.evaluateTableObj.lateCount,
      missCount: this.evaluateTableObj.missCount,
      content: this.evaluateTableObj.content,
      sourceIdList
    };
    this.http.submitStartEvaluate(obj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.view = false;
        this.page(this.pageInfo);
      }
    });
  }
}

class SearchParams {
  schoolYear: string;
  semester: any;
  number: string;
  name: string;
  teacher: string;
  state: any = '';
}


class EvaluateTableObj {
  evaluteDate: string;
  startSection: number;
  endSection: number;
  shouldCount = 0;
  realCount = 0;
  lateCount = 0;
  missCount = 0;
  content: string;
  courseId: string;
  courseName: string;
}
